/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.chanceit.ssss.fragments;

import net.tsz.afinal.http.AjaxCallBack;

import org.gl.GlobalVariable;
import org.gl.customview.EditView;
import org.gl.utils.Dateutil;
import org.gl.utils.lg;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.chanceit.ssss.activity.R;
import com.chanceit.ssss.common.IntentExtraDataKey;
import com.chanceit.ssss.common.IntentExtraDataKeyValue;
import com.chanceit.ssss.data.DataSources;
import com.chanceit.ssss.dialog.DateTimePickerDialog;

public class CarerProjectUpdateFragment extends BaseFragment implements
		View.OnClickListener {
	public final static String ARG_POSITION = "position";
	int mCurrentPosition = -1;
	String TAG = "CarerProjectUpdateFragment";
	/**
	 * set for current km next km next time
	 */
	EditText ck, nk, carer_car_plate, project_record_time;
	// DatePicker nt;
	EditView nt;
	RadioGroup radioGroup_project_type;
	private String plate;
	JSONObject carInfo;
	JSONObject carer;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		// If activity recreated (such as from screen rotate), restore
		// the previous article selection set by onSaveInstanceState().
		// This is primarily necessary when in the two-pane layout.
		if (savedInstanceState != null) {
			mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
		}
		try {
			carer = IntentExtraDataKeyValue.getUserInfoToIntent();
			carInfo = IntentExtraDataKeyValue.getUserInfoToIntent()
					.getJSONObject("car");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		plate = GlobalVariable.getGlobalInstance().intent
				.getStringExtra(IntentExtraDataKey.PLATE);
		view = inflater
				.inflate(R.layout.carer_project_update, container, false);
		ck = (EditText) view.findViewById(R.id.project_current_km);
		nk = (EditText) view.findViewById(R.id.project_next_km);
		nt = ((EditView) view.findViewById(R.id.project_next_date));
		
		radioGroup_project_type = (RadioGroup) view
				.findViewById(R.id.radioGroup_project_type);
		radioGroup_project_type.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				int type = getUpdateProjectType();
				if(type ==0)
				{
					nk.setText(carInfo.optInt("maintainKilometer") + "");
					String nt_cal = Dateutil
							.getTimeString(
									Dateutil.SimpleDateFormat__YYYYMMDD,
									Dateutil.convert2long(
											Dateutil.getNextDayString(carInfo
													.optInt("maintainTime") * 30),
											null));
					nt.getEditView().setText(nt_cal);
				}else{
					nk.setText(carer.optInt("maintainMileage") + "");
					nt.getEditView().setText(""+carer
							.optString("maintainTime"));
				}
				
			}
		});
		
		carer_car_plate = (EditText) view.findViewById(R.id.carer_car_plate);
		carer_car_plate.setText(plate);
		project_record_time = (EditText) view
				.findViewById(R.id.project_record_time);
		new DateTimePickerDialog(context, project_record_time);
		project_record_time.setFocusable(false);
		project_record_time.setText(Dateutil.getTimeString(
				Dateutil.SimpleDateFormat__YYYYMMDDHHMMSS,
				System.currentTimeMillis()));
		// TODO get he user plate
		// nt = (DatePicker) view.findViewById(R.id.project_next_time);
		// final Calendar c = Calendar.getInstance();
		// nt.init(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
		// c.get(Calendar.DAY_OF_MONTH), null);
		(view.findViewById(R.id.project_update_button))
				.setOnClickListener(this);
		ck.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {

				try {
					CharSequence value = s;
					if (TextUtils.isEmpty(value)) {
						value = "0";
					}
					if (TextUtils.isDigitsOnly(value) && carInfo != null) {
						int ckm = Integer.parseInt(value.toString());
						// "firstMaintainKilometer":5000,"firstMaintainTime":1,"maintainKilometer":5500,"maintainTime":1
						// long current = Dateutil.convert2long(s., format)
						// if (ckm<carInfo.optInt("firstMaintainKilometer")) {
						// nk.setText(carInfo.optInt("firstMaintainKilometer")+"");
						// nt.getEditView().setText(nt_cal);
						// }else
						int type = getUpdateProjectType();
						if(type ==0)
						{
							nk.setText(ckm
									+ carInfo.optInt("maintainKilometer") + "");
//							String nt_cal = Dateutil
//									.getTimeString(
//											Dateutil.SimpleDateFormat__YYYYMMDD,
//											Dateutil.convert2long(
//													Dateutil.getNextDayString(carInfo
//															.optInt("maintainTime") * 30),
//													null));
//							nt.getEditView().setText(nt_cal);
						}else{
//							nk.setText(carer.optInt("maintainMileage") + "");
//							nt.getEditView().setText(carer
//									.optInt("maintainTime"));
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

			
			
			}
		});
		initData();
		return view;
	}

	private void initData() {
		int type = getUpdateProjectType();
		if(type ==0)
		{
			nk.setText(carInfo.optInt("maintainKilometer") + "");
			String nt_cal = Dateutil
					.getTimeString(
							Dateutil.SimpleDateFormat__YYYYMMDD,
							Dateutil.convert2long(
									Dateutil.getNextDayString(carInfo
											.optInt("maintainTime") * 30),
									null));
			nt.getEditView().setText(nt_cal);
		}else{
			nk.setText(carer.optInt("maintainMileage") + "");
			nt.getEditView().setText(""+carer
					.optString("maintainTime"));
		}
		
	}

	private void updateProject() {
		DataSources ds = new DataSources();
		int id = GlobalVariable.getGlobalInstance().intent.getIntExtra(
				IntentExtraDataKey.USERID, 0);
		String maintainMileage = nk.getText().toString();
		
		String maintainTime = nt.getEditView().getText().toString();
		String currentMileage = ck.getText().toString();
		// if (TextUtils.isEmpty(plate)) {
		// nk.setError(getString(R.string.error_field_required));
		// nk.requestFocus();
		// Toast.makeText(getActivity(), R.string.carer_plate_required,
		// Toast.LENGTH_SHORT).show();
		// return;
		// }
		if (TextUtils.isEmpty(maintainMileage)) {
			nk.setError(getString(R.string.error_field_required));
			nk.requestFocus();
			return;
		}
		if (TextUtils.isEmpty(maintainTime)) {
			nt.getEditView().setError(getString(R.string.error_field_required));
			nt.getEditView().requestFocus();
			return;
		}
		if (TextUtils.isEmpty(currentMileage)) {
			ck.setError(getString(R.string.error_field_required));
			ck.requestFocus();
			return;
		}
		int type = getUpdateProjectType();
		if (type==0) {
			type =1;
		}else{
			type=0;//FIXME 修复紧急保养和维修的问题
		}
		ds.updateProject(String.valueOf(id), plate, maintainMileage,
				maintainTime, currentMileage, project_record_time.getText().toString(),type, new AjaxCallBack<String>() {

					@Override
					public void onStart() {
						super.onStart();
						loading();
					}

					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						lg.i(TAG, t);
						int isfinish = 0;
						String message = "";
						try {
							JSONObject j = new JSONObject(t);
							isfinish = j.optInt("code");
							message += j.optString("reason");
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							if (isfinish != 0) {
								loadFailed(message);
							} else {
								loadSuccessed();
								getActivity().onBackPressed();
							}
						}

					}

					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						super.onFailure(t, errorNo, strMsg);
						Toast.makeText(getActivity(), R.string.err_unknow,
								Toast.LENGTH_SHORT).show();
						loadFailed(strMsg);
					}

				});

	}
	/**
	 * 1.紧急维修; 0.保养
	 * @return 
	 */
	private int getUpdateProjectType() {
		if (null==radioGroup_project_type) {
			return 0;
		}
		return radioGroup_project_type.getCheckedRadioButtonId() == R.id.radio0 ? 0
				: 1;
	}

	@Override
	public void loadSuccessed() {
		super.loadSuccessed();
		Toast.makeText(getActivity(), R.string.carer_update_project_ok,
				Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onStart() {
		super.onStart();

		// During startup, check if there are arguments passed to the fragment.
		// onStart is a good place to do this because the layout has already
		// been
		// applied to the fragment at this point so we can safely call the
		// method
		// below that sets the article text.
		Bundle args = getArguments();
		if (args != null) {
			// Set article based on argument passed in
			updateArticleView(args.getInt(ARG_POSITION));
		} else if (mCurrentPosition != -1) {
			// Set article based on saved instance state defined during
			// onCreateView
			updateArticleView(mCurrentPosition);
		}
	}

	public void updateArticleView(int position) {
		// TextView article = (TextView)
		// getActivity().findViewById(R.id.article);
		// article.setText(Ipsum.Articles[position]);
		// mCurrentPosition = position;
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		// Save the current article selection in case we need to recreate the
		// fragment
		outState.putInt(ARG_POSITION, mCurrentPosition);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.project_update_button:
			updateProject();
			break;

		default:
			break;
		}

	}
}